package klochkov.snake.model;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;

import klochkov.snake.common.*;

/**
 * Represents the snake. The snake can eat frogs.
 * 
 * @author Dmitry_Klochkov
 * 
 */
public class Snake extends Entity {
	private final ArrayList<EntityCell> cells = new ArrayList<EntityCell>();
	private final Game game;
	private Direction direction = Direction.RIGTH;

	public Snake(Game game, int length) {
		super(game);
		this.game = game;
		for (int i = 0; i < length; i++) {
			if (i == 0) {
				cells.add(new EntityCell(this, CellType.SNAKE_HEAD));
			}else if((i==length-1)&&(length>1)){
				cells.add(new EntityCell(this, CellType.SNAKE_TAIL));
			}else{
				cells.add(new EntityCell(this, CellType.SNAKE_BODY));
			}
		}
	}

	public ArrayList<EntityCell> getCells() {
		return cells;
	}
	
	public void moveTo(int x, int y){
		removeFromField();
		int bufX;
		int bufY;
		int newX = x;
		int newY = y;
		for(EntityCell c: cells){
			bufX = c.getX();
			bufY = c.getY();
			c.setX(newX);
			c.setY(newY);
			newX = bufX;
			newY = bufY;
		}
		allocateOnField();
		
	}
	
	private void removeFromField()
	{
		for(EntityCell c:cells){
			game.getGameField()[c.getY()][c.getX()].clear();
		}
	}
	
	private void allocateOnField(){
		for(EntityCell c:cells){
			game.getGameField()[c.getY()][c.getX()].setEntityCell(c);
		}
	}
	
	

	@Override
	public void move() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {}
		
		Point nextCell = new Point();
		int curX = cells.get(0).getX();
		int curY = cells.get(0).getY();
		int nextX;
		int nextY;
		boolean curLock;
		boolean nextLock;
		
		nextCell = game.calcNextCell(curX, curY, direction);
		nextX = nextCell.x;
		nextY = nextCell.y;
		CellType cType;
		
		if (game.isField(nextX, nextY)) {
			while (true) {
				curLock = game.tryLock(curX, curY);
				nextLock = game.tryLock(nextX, nextY);

				if (curLock && nextLock) {
					if (game.isEmpty(nextX, nextY)) {
						moveTo(nextX, nextY);
						game.unlock(curX, curY);
						game.unlock(nextX, nextY);
						break;
					} else {
						cType = game.getCellType(nextX, nextY);
						if (cType==CellType.SNAKE_BODY
								&&cType==CellType.SNAKE_TAIL) {
							//GAME OVER
							game.stop();
						}else if(cType == CellType.FROG){
							//Teleport the frog,update score, grow up the snake
							
							
						}
					}
				} else {
					if (curLock) {
						game.unlock(curX, curY);
					}
					if (nextLock) {
						game.unlock(nextX, nextY);
					}
				}
			}
		} else {
			// GAME OVER
			game.stop();
		}
		
		

	}
}


